package com.fire.control.system.module.device.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fire.control.system.config.redis.RedisService;
import com.fire.control.system.dto.CountDto;
import com.fire.control.system.dto.DeviceDTO;
import com.fire.control.system.dto.DeviceGroupDTO;
import com.fire.control.system.dto.DeviceListDTO;
import com.fire.control.system.dto.GroupListDTO;
import com.fire.control.system.dto.MaintenceListDTO;
import com.fire.control.system.dto.MapDeviceDTO;
import com.fire.control.system.dto.MqttDev;
import com.fire.control.system.dto.UserDTO;
import com.fire.control.system.dto.WarningHandleDTO;
import com.fire.control.system.dto.app.AppDeviceVo;
import com.fire.control.system.entity.Area;
import com.fire.control.system.entity.Company;
import com.fire.control.system.entity.Device;
import com.fire.control.system.entity.DeviceGroup;
import com.fire.control.system.entity.DeviceType;
import com.fire.control.system.entity.Gateway;
import com.fire.control.system.entity.User;
import com.fire.control.system.entity.WarningHandle;
import com.fire.control.system.entity.WarningInfo;
import com.fire.control.system.module.company.dao.CompanyMapper;
import com.fire.control.system.module.company.service.CompanyService;
import com.fire.control.system.module.device.dao.DeviceGroupMapper;
import com.fire.control.system.module.device.dao.DeviceGroupRepository;
import com.fire.control.system.module.device.dao.DeviceMapper;
import com.fire.control.system.module.device.dao.DeviceRepository;
import com.fire.control.system.module.device.dao.GatewayMapper;
import com.fire.control.system.module.device.service.DeviceService;
import com.fire.control.system.module.device.service.DeviceTypeService;
import com.fire.control.system.module.file.dao.FileMapper;
import com.fire.control.system.module.user.dao.UserMapper;
import com.fire.control.system.module.warning.dao.WarningHandleMapper;
import com.fire.control.system.module.warning.dao.WarningHandleRepository;
import com.fire.control.system.module.warning.dao.WarningInfoMapper;
import com.fire.control.system.module.warning.dao.WarningMapper;
import com.fire.control.system.module.warning.service.WarningService;
import com.fire.control.system.statics.Key;
import com.fire.control.system.statics.ResponseMessage;
import com.fire.control.system.statics.Status_Online;
import com.fire.control.system.statics.Type_Solution;
import com.fire.control.system.statics.Type_Warning;
import com.fire.control.system.support.protocol.comman.ProtocolSelector;
import com.fire.control.system.support.protocol.comman.ResponseProtocol;
import com.fire.control.system.support.protocol.device.DeviceRequestProtocol;
import com.fire.control.system.support.util.ResultPageUtil;
import com.fire.control.system.support.util.StaticValue;
import com.fire.control.system.support.util.XdaoDate;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;



/**
 * 
 * @ClassName:  DeviceServiceImpl
 * @Description:  设备管理业务实现类
 * @author:  xiechengguang
 * @date:  2017年5月6日 上午9:39:40
 *
 */
@Service("deviceService")
public class DeviceServiceImpl implements DeviceService {
	@Autowired private CompanyMapper companyMapper;
	@Autowired private DeviceRepository deviceRepository;
	@Autowired private DeviceGroupRepository deviceGroupRepository;
	@Autowired private DeviceGroupMapper deviceGroupMapper;
	@Autowired private DeviceMapper deviceMapper;
	@Autowired private UserMapper userMapper;
	@Autowired private WarningMapper warningMapper;
	@Autowired private ProtocolSelector protocolSelector;
	@Autowired private DeviceTypeService deviceTypeService;
	@Autowired private WarningHandleRepository warningHandleRepository;
	@Autowired private FileMapper fileMapper;
	@Autowired private GatewayMapper gatewayMapper;
	@Autowired private RedisService redisService;
	@Autowired private WarningHandleMapper warningHandleMapper;
	@Autowired private WarningInfoMapper warningInfoMapper;
	@Autowired private WarningService warningService;
	@Autowired private CompanyService companyService;
	
	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static final Logger logger = LoggerFactory.getLogger(DeviceServiceImpl.class);
	
	/**
	* @Title: deviceDetection
	* @Description: TODO(设备离线检测job)
	* @author wanbo
	* @date  2017年6月29日 下午8:16:11
	*/
	public void deviceDetection(){
		List<Device> devices = deviceMapper.getDeviceDetectionList();
		for (Device device : devices) {
			MqttDev dev = redisService.getObject(Key.redis_key_lora_devEUI_+device.getSerialNumber(), MqttDev.class);
			if(dev!=null){
				long minutes = (new Date().getTime() - dev.getReceiveTime().getTime()) /(1000 * 60);
				if(minutes>StaticValue.offline_duration_minutes){
					logger.info("--->【注意】报警了 检测到设备离线已超过"+StaticValue.offline_duration_minutes+"分钟,deviceId:"+device.getId()+" devEUI:"+dev.getDevEUI());
					warningService.insertWarning(device.getId(), Status_Online.offline.toString(), Type_Warning.device_fault.toString(), "no_connect", new Date(), "");
				}
			}
		}
	}
	
	
	/**
	 * <p>Title: getSysCount</p> 
	 * <p>Description: 获取系统数据统计  </p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.business.service.DeviceService#getSysCount(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol getSysCount(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		Map<String, Object> map = new HashMap<String, Object>();
		
		String comId = user.getCompany().getId(); // 当前用户所属企业id
		List<String> companyIds = this.companyService.getChildCompanyIdList(comId);
		String companyId = requestProtocol.getCompanyId();  // 下拉选择的企业id
		
		// 总设备数                                                    
		int deviceCount = deviceMapper.countByCompanyId(companyId, companyIds);
		// 在线设备数
		int deviceOnLineCount = deviceMapper.countOnLine(companyId, companyIds);
		// 离线设备数
		int deviceOffLineCount = deviceCount - deviceOnLineCount;
		map.put("deviceCount", deviceCount);
		map.put("deviceOnLineCount", deviceOnLineCount);
		map.put("deviceOffLineCount", deviceOffLineCount);
		
		// 火灾报警数
		int fireAlarmCount = warningMapper.countFireAlarm(companyId, companyIds);
		// 故障报警数
		int deviceFaultCount = warningMapper.countDeviceFault(companyId, companyIds);
		// 设备报警数
		int warningCount = fireAlarmCount + deviceFaultCount;
		map.put("fireAlarmCount", fireAlarmCount);
		map.put("deviceFaultCount", deviceFaultCount);
		map.put("warningCount", warningCount);
		
		/*// 火灾报警
		List<AppRespWarningVo> fireWarnings = warningMapper.fireWarnings(companyId);
		if(fireWarnings != null) {
			int fireWarningsCount = fireWarnings.size();
			map.put("fireWarningsCount", fireWarningsCount);
//			map.put("fireWarnings", fireWarnings);
		}
		// 设备故障
		List<AppRespWarningVo> deviceFault = warningMapper.deviceFault(companyId);
		if(deviceFault != null) {
			int deviceFaultCount = deviceFault.size();
			map.put("deviceFaultCount", deviceFaultCount);
//			map.put("deviceFault", deviceFault);
		}*/
		
		respProtocol.setData(map);
		ResponseMessage.CODE_200.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	
	/**
	 * 
	 * @Title: getDeviceList   
	 * @Description: 获取设备列表  
	 * @param:  requestProtocol     
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol getDeviceList(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		
		int page = requestProtocol.getCurrentPage();
		int size = requestProtocol.getPageSize();
		String groupId = requestProtocol.getGroupId();
		
		PageHelper.startPage(page, size);
		List<DeviceListDTO> deviceList = deviceMapper.getDeviceList(groupId);
		
		respProtocol.setData(ResultPageUtil.resultPage(new PageInfo<DeviceListDTO>(deviceList), deviceList));
		return respProtocol;
	}
	
	/**
	 * 
	 * @Title: searchDevices   
	 * @Description: 按条件搜索设备列表  
	 * @param:  requestProtocol      
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol searchDevices(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		
		int page = requestProtocol.getCurrentPage();
		int size = requestProtocol.getPageSize();
		PageHelper.startPage(page, size);
		
		String deviceName = requestProtocol.getDeviceName();
		String groupId = requestProtocol.getGroupId();
		String onlineStatus = requestProtocol.getOnlineStatus();

//		String companyId = user.getCompany().getId();
		List<DeviceListDTO> list = deviceMapper.searchDevices(deviceName, groupId, onlineStatus);
		if(list != null && !list.isEmpty()) {
			respProtocol.setData(ResultPageUtil.resultPage(new PageInfo<DeviceListDTO>(list), list));
			return respProtocol;
		}
		ResponseMessage.CODE_204.messageToProtocol(respProtocol);
		return respProtocol;
	}
	
	
	/**
	 * 
	 * @Title: getDeviceInfo   
	 * @Description: 获取设备详细信息  
	 * @param:  requestProtocol      
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol getDeviceInfo(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String id = requestProtocol.getId();
		if(null != id){
			DeviceDTO deviceDTO = deviceMapper.getDetailById(id);
			if(null != deviceDTO) {
				String region = deviceDTO.getAreaAddr();
				if(region != null) {
					deviceDTO.setRegion(region.split(","));
				}
				if(deviceDTO.getPlanUrl() != null) {
					deviceDTO.setPlanUrl(StaticValue.file_server_domain + deviceDTO.getPlanUrl());
				}
				ResponseMessage.CODE_200.messageToProtocol(respProtocol);
				respProtocol.setData(deviceDTO);
				return respProtocol;
			}
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		return respProtocol;
	}
	
	/**
	 * @throws Exception 
	 * 
	 * @Title: updateDeviceInfo   
	 * @Description: 修改设备信息  
	 * @param:  requestProtocol      
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Transactional
	@Override
	public ResponseProtocol updateDeviceInfo(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String id = requestProtocol.getId();
		Device device = deviceMapper.getById(id);
		if(null != device) {
			device = this.setDevice(device, requestProtocol);
			device.setUpdateTime(new Date());
			deviceMapper.updateDevice(device);
			
			ResponseMessage.CODE_200.messageToProtocol(respProtocol);
			respProtocol.setDate(new XdaoDate());
			return respProtocol;
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	
	/**
	 * @throws IOException 
	 * 
	 * @Title: setDevice   
	 * @Description: 新增或者修改设备公共方法 
	 * @param:        
	 * @return: Device      
	 * @throws
	 */
	private Device setDevice(Device device, DeviceRequestProtocol requestProtocol) {
		
		DeviceType deviceType = deviceTypeService.getDeviceTypeById(StaticValue.device_type_id);
		
		device.setDeviceType(deviceType);
		Area area = deviceMapper.getAreaById(requestProtocol.getAreaId());
		device.setArea(area);
		device.setCityId(requestProtocol.getCityId());
		device.setProvinceId(requestProtocol.getProvinceId());
		String region = area.getMergerName();
		device.setBuilding(region+requestProtocol.getAddress()); //保存区域+详细地址  作为完整地址（确定某栋楼的具体地址）
		device.setDeviceName(requestProtocol.getDeviceName());
		device.setDeviceType(deviceType);
		
		device.setAddress(requestProtocol.getAddress()); //详细地址
		device.setSerialNumber(requestProtocol.getSerialNumber());
		device.setOwner(requestProtocol.getOwner());
		device.setPhone(requestProtocol.getPhone());
		//TODO  所在户型位置
		Gateway gateway = gatewayMapper.getById(requestProtocol.getGatewayId());
		device.setGateway(gateway);
		//通过公司id查找到公司
		Company company = companyMapper.getById(requestProtocol.getCompanyId());
		device.setCompany(company);
		
		//通过设备组id查找到设备组
		DeviceGroup dg = deviceGroupRepository.findOne(requestProtocol.getGroupId());
		device.setDeviceGroup(dg);
		
		// 安全管理员、巡检员
		User securityManager = userMapper.getUserById(requestProtocol.getManagerId());
		User securityPatrol = userMapper.getUserById(requestProtocol.getPatrolId());
		device.setSecurityManager(securityManager);
		device.setSecurityPatrol(securityPatrol);
		
		device.setPlanId(requestProtocol.getPlanId());
		device.setPlanUrl(requestProtocol.getUrl());
		
		device.setSideId(requestProtocol.getSideId());
		device.setLongitude(requestProtocol.getLongitude());
		device.setLatitude(requestProtocol.getLatitude());
		device.setFloor(requestProtocol.getFloor());
		device.setFloorMax(requestProtocol.getFloorMax());
		device.setPlaneX(requestProtocol.getPlanX());
		device.setPlaneY(requestProtocol.getPlanY());
		device.setSideX(requestProtocol.getSideX());
		device.setSideY(requestProtocol.getSideY());
		
		return device;
	}
	
	/**
	 * 
	 * @Title: addDevice   
	 * @Description: 新增设备  
	 * @param:  requestProtocol      
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol addDevice(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		if(null != requestProtocol) {
			Device device = new Device();
			device = this.setDevice(device, requestProtocol);
			// 默认为正常
			device.setOnlineStatus(Status_Online.normal);
			Device newDevice = deviceRepository.save(device);
			if(null != newDevice) {
				ResponseMessage.CODE_200.messageToProtocol(respProtocol);
				respProtocol.setDate(new XdaoDate());
				return respProtocol;     
			}
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	
	/**
	 * 
	 * @Title: deleteDevice   
	 * @Description: 删除一个或一组设备，删除，实际上是将status改为false  
	 * @param:  requestProtocol     
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol deleteDevice(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String[] ids = requestProtocol.getIds();
		if(null != ids && ids.length > 0) {
			int n = 0;
			for(String id : ids) {
				int i = deviceMapper.updateDeviceStatus(id);
				n = n + i;
			}
			if(n == ids.length) {
				ResponseMessage.CODE_200.messageToProtocol(respProtocol);
				respProtocol.setDate(new XdaoDate());
				return respProtocol;
			}
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	
	/**
	 * 
	 * @Title: getDeviceGroupList   
	 * @Description: 获取设备组列表  
	 * @param:  requestProtocol      
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol getDeviceGroupList(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		int page = requestProtocol.getCurrentPage();
		int size = requestProtocol.getPageSize();
		PageHelper.startPage(page, size);
		String companyId = user.getCompany().getId();
		List<GroupListDTO> groupList = deviceGroupMapper.getDeviceGroupList(companyId);
		if(groupList != null && !groupList.isEmpty()) {
			respProtocol.setData(ResultPageUtil.resultPage(new PageInfo<GroupListDTO>(groupList), groupList));
			return respProtocol;
		}
		ResponseMessage.CODE_204.messageToProtocol(respProtocol);
		return respProtocol;
	}

	/**
	 * 
	 * @Title: addDeviceGroup   
	 * @Description: 新增设备组  
	 * @param:  requestProtocol     
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Transactional
	@Override
	public ResponseProtocol addDeviceGroup(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		if(null != requestProtocol) {
			DeviceGroup deviceGroup = new DeviceGroup();
			requestProtocol.setCompanyId(user.getCompany().getId());
			deviceGroup = this.setDeviceGroup(deviceGroup, requestProtocol);
			
			DeviceGroup newDeviceGroup = deviceGroupRepository.save(deviceGroup);
			// 建立用户设备组的关系
			deviceGroupMapper.saveUserGroup(deviceGroup.getId(), user.getUserId());
			
			ResponseMessage.CODE_200.messageToProtocol(respProtocol);
				respProtocol.setDate(new XdaoDate());
				return respProtocol;
		}
		
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	
	/**
	 * 
	 * @Title: updateDeviceGroupInfo   
	 * @Description: 修改设备组信息  
	 * @param:  requestProtocol      
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol updateDeviceGroupInfo(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		if(null != requestProtocol) {
			String id = requestProtocol.getId();
			DeviceGroup deviceGroup = deviceGroupRepository.findOne(id);
			if(null != deviceGroup) {
				requestProtocol.setCompanyId(user.getCompany().getId());
				deviceGroupMapper.updateDeviceGroupInfo(this.setDeviceGroup(deviceGroup, requestProtocol));
				
				ResponseMessage.CODE_200.messageToProtocol(respProtocol);
				respProtocol.setDate(new XdaoDate());
				return respProtocol;
			}
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	
	/**
	 * @author: xiechengguang 
	 * @Title: setDeviceGroup   
	 * @Description: 添加、修改设备组公共方法  
	 * @param:        
	 * @return: DeviceGroup      
	 * @throws
	 */
	private DeviceGroup setDeviceGroup(DeviceGroup deviceGroup, DeviceRequestProtocol requestProtocol) {
		deviceGroup.setGroupName(requestProtocol.getGroupName());
		deviceGroup.setGroupDesc(requestProtocol.getDescription());
		
		Company company = companyMapper.getById(requestProtocol.getCompanyId());
		deviceGroup.setCompany(company);
		
		deviceGroup.setCityId(requestProtocol.getCityId());
		deviceGroup.setProvinceId(requestProtocol.getProvinceId());
		
		// 所属组
		deviceGroup.setParentId(requestProtocol.getParentId());
		// 区域（省市县区）
		Area area = deviceMapper.getAreaById(requestProtocol.getAreaId());
		deviceGroup.setArea(area);
		deviceGroup.setAddress(requestProtocol.getAddress());
		
		deviceGroup.setLongitude(requestProtocol.getLongitude());
		deviceGroup.setLatitude(requestProtocol.getLatitude());
			
		return deviceGroup;
	}
	
	/**
	 * 
	 * @Title: deleteDeviceGroup   
	 * @Description: 删除设备组 ,删除，实际上是将status改为false   
	 * @param:  requestProtocol      
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol deleteDeviceGroup(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String[] ids = requestProtocol.getIds();
		if(null != ids && ids.length > 0) {
			int n = 0;
			for(String id : ids) {
				int i = deviceGroupMapper.deleteById(id);
				n = n + i;
			}
			if(n == ids.length) {
				ResponseMessage.CODE_200.messageToProtocol(respProtocol);
				respProtocol.setDate(new XdaoDate());
				return respProtocol;
			}
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	
	/**
	 * 
	 * @Title: searchDeviceGroups   
	 * @Description: 搜索设备组  
	 * @param:  requestProtocol      
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol searchDeviceGroups(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		
		int page = requestProtocol.getCurrentPage();
		int size = requestProtocol.getPageSize();
		
		List<String> companyIds = this.companyService.getChildCompanyIdList(user.getCompany().getId());
		String groupName  = requestProtocol.getGroupName();
		
		PageHelper.startPage(page, size);
		List<GroupListDTO> deviceGroupList = deviceGroupMapper.searchDeviceGroups(groupName, companyIds);
		respProtocol.setData(ResultPageUtil.resultPage(new PageInfo<GroupListDTO>(deviceGroupList), deviceGroupList));
		return respProtocol;
	}
	
	/**
	 * 
	 * @Title: searchDeviceByName   
	 * @Description: 根据设备名称查找设备  
	 * @param:  requestProtocol     
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol searchDeviceByName(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		if(null != requestProtocol) {
			String searchKey = requestProtocol.getSearchKey();
			int page = requestProtocol.getCurrentPage();
			int size = requestProtocol.getPageSize();
			String comId = user.getCompany().getId(); // 当前用户所属企业id
			List<String> companyIds = this.companyService.getChildCompanyIdList(comId);
			String companyId = requestProtocol.getCompanyId();  // 下拉选择的企业id
			
			PageHelper.startPage(page, size);
			List<MapDeviceDTO> deviceList= deviceMapper.searchDeviceByName(searchKey, companyId, companyIds);
			
			if(deviceList != null && !deviceList.isEmpty()) {
				PageInfo<MapDeviceDTO> pageInfo = new PageInfo<MapDeviceDTO>(deviceList);
				respProtocol.setData(ResultPageUtil.resultPage(pageInfo, deviceList));
				return respProtocol;    
			}
			ResponseMessage.CODE_204.messageToProtocol(respProtocol);
			respProtocol.setDate(new XdaoDate());
			return respProtocol; 
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		return respProtocol;
	}
	
	
	
	
	/**
	 * 
	 * @Title: getDeviceMaintenceList   
	 * @Description: 维保设备列表  
	 * @param:  requestProtocol      
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol getDeviceMaintenceList(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		
		int page = requestProtocol.getCurrentPage();
		int size = requestProtocol.getPageSize();
		PageHelper.startPage(page, size);
		
		String companyId = user.getCompany().getId();
		
		List<MaintenceListDTO> maintenceList = warningMapper.getAllByCompanyId(companyId);
		
		if(maintenceList != null && !maintenceList.isEmpty()) {
			ResponseMessage.CODE_200.messageToProtocol(respProtocol);
			respProtocol.setDate(new XdaoDate());
			respProtocol.setData(ResultPageUtil.resultPage(new PageInfo<MaintenceListDTO>(maintenceList), maintenceList));
			return respProtocol;
		}
		ResponseMessage.CODE_204.messageToProtocol(respProtocol);
		return respProtocol;
	}
	
	/**
	 * 
	 * @Title: deleteDeviceMaintence   
	 * @Description: 删除维保设备信息 ,删除，实际上是将status改为false   
	 * @param:  requestProtocol      
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol deleteDeviceMaintence(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String[] ids = requestProtocol.getIds();
		if(null != ids && ids.length > 0) {
			int n = 0;
			for(String id : ids) {
				int i = warningMapper.updateWarningInfoStatus(id);
				n = n + i;
			}
			if(n == ids.length) {
				ResponseMessage.CODE_200.messageToProtocol(respProtocol);
				respProtocol.setDate(new XdaoDate());
				return respProtocol;
			}
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	
	/**
	 * 
	 * @Title: getDeviceMaintenceInfo   
	 * @Description: 维保设备处理详细信息  
	 * @param:  requestProtocol      
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol getDeviceMaintenceInfo(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String id = requestProtocol.getId();
		if(null != id){
			WarningHandleDTO handleInfo = warningMapper.getHandleInfo(id);
			if(handleInfo != null) {
				if(handleInfo.getTrustees() == null) {
					handleInfo.setTrustees(user.getName());
				}
				List<String> urls = warningHandleMapper.getHandleFiles(handleInfo.getId());
				
				handleInfo.setUrls(this.absoluteUrls(urls));
			}
			ResponseMessage.CODE_200.messageToProtocol(respProtocol);
			respProtocol.setDate(new XdaoDate());
			respProtocol.setData(handleInfo);
			return respProtocol;
		}
		ResponseMessage.CODE_400.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	
	/**
	 * @author: xiechengguang 
	 * @Title: absoluteUrls   
	 * @Description: 返回绝对路径  
	 * @param:        
	 * @return: List<String>      
	 * @throws
	 */
	public List<String> absoluteUrls(List<String> urls) {
		List<String> returnUrls = new ArrayList<String> ();
		
		if(urls != null && !urls.isEmpty()) {
			for(String url : urls) {
				url = StaticValue.file_server_domain + url;
				returnUrls.add(url);
			}
		}
		return returnUrls;
	}
	
	/**
	 * 
	 * @Title: handleDeviceMaintence   
	 * @Description: 维保处理  
	 * @param:  requestProtocol      
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Transactional
	@Override
	public ResponseProtocol handleDeviceMaintence(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		String id = requestProtocol.getId();
		WarningInfo warningInfo = warningMapper.findById(id);
		WarningHandle handle = new WarningHandle();
		handle.setUserId(user.getUserId());
		
		// 完成处理（设备onlineStatus改为‘normal’,报警信息currentStatus改为‘complete’）
		int res = warningInfoMapper.finishWarning(id);
		
		handle.setWarningInfo(warningInfo);
		// web端，此处为“处理”
		handle.setSolutionType(Type_Solution.valueOf("dispose"));
		String endTime = requestProtocol.getEndTime();
		
		try {
			handle.setEndTime(format.parse(endTime));
		} catch (ParseException e) {
			logger.info("日期转换错误");
		}
		if(requestProtocol.getTrustees() != null && requestProtocol.getTrustees() != "") {
			handle.setTrustees(requestProtocol.getTrustees());
		} else {
			handle.setTrustees(user.getName());
		}
		
		handle.setSolutionDesc(requestProtocol.getSolutionDesc());
		
		int result = warningHandleMapper.saveBean(handle);
		// 保存文件---与处理记录的对应关系
		String[] ids = requestProtocol.getIds();
		if(ids != null && ids.length > 0) {
			for(String fid : ids) {
				fileMapper.saveFileAndObject(fid, handle.getId());
			}
		}
		
		ResponseMessage.CODE_200.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	
	/**
	 * 
	 * @Title: searchDeviceMaintences   
	 * @Description: 按条件搜索维保设备列表  
	 * @param:  requestProtocol      
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol searchDeviceMaintences(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		
		int page = requestProtocol.getCurrentPage();
		int size = requestProtocol.getPageSize();
		String companyId = user.getCompany().getId();
		List<String> companyIds = this.companyService.getChildCompanyIdList(companyId);
		requestProtocol.setCompanyIds(companyIds);
		
		PageHelper.startPage(page, size);
		List<MaintenceListDTO> list = warningMapper.searchDeviceMaintences(requestProtocol);
		if(list != null & !list.isEmpty()) {
			respProtocol.setData(ResultPageUtil.resultPage(new PageInfo<MaintenceListDTO>(list), list));
			return respProtocol;
		}
		ResponseMessage.CODE_204.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
		
	}
	
	/**
	 * 
	 * @Title: getDeviceGroups   
	 * @Description: 获取设备组，不分页  ，用于下拉选
	 * @param:  requestProtocol      
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol getDeviceGroups(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol respProtocol = protocolSelector.choose(requestProtocol);
		List<DeviceGroup> deviceGroupList = deviceGroupRepository.getDeviceGroups();
		if(null != deviceGroupList & deviceGroupList.size() > 0) {
			List<DeviceGroupDTO> groupDtoList = new ArrayList<DeviceGroupDTO>();
			for(DeviceGroup group : deviceGroupList) {
				DeviceGroupDTO groupDto = new DeviceGroupDTO();
				groupDto.setDeviceGroup(group);
				groupDtoList.add(groupDto);
			}
			respProtocol.setData(groupDtoList);
			ResponseMessage.CODE_200.messageToProtocol(respProtocol);
			respProtocol.setDate(new XdaoDate());
			return respProtocol;
		}
		ResponseMessage.CODE_204.messageToProtocol(respProtocol);
		respProtocol.setDate(new XdaoDate());
		return respProtocol;
	}
	
	@Override
	public DeviceDTO getBydevEUI(String devEUI){
		return deviceMapper.getBydevEUI(devEUI);
	}
	
	@Override
	public DeviceDTO getBydevId(String devId){
		return deviceMapper.getBydevId(devId);
	}


	/**
	 * <p>Author: xiechengguang</p> 
	 * <p>Title: getDevices</p> 
	 * <p>Description: 获取所有设备</p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.device.service.DeviceService#getDevices(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol getDevices(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		
		String comId = user.getCompany().getId(); // 当前用户所属企业id
		List<String> companyIds = this.companyService.getChildCompanyIdList(comId);
		String companyId = requestProtocol.getCompanyId();  // 下拉选择的企业id
		
		List<AppDeviceVo> devices = deviceMapper.findByCompanyId(companyId, companyIds); // companyId命名不能更改
		if(devices !=null && !devices.isEmpty()) {
			ResponseMessage.CODE_200.messageToProtocol(response);
			response.setDate(new XdaoDate());
			response.setData(devices);
			return response;
		}
		ResponseMessage.CODE_204.messageToProtocol(response);
		return response;
		
	}

	/**
	 * <p>Author: xiechengguang</p> 
	 * <p>Title: getDeviceGroupInfo</p> 
	 * <p>Description: 根据id获取设备组详细信息</p> 
	 * @param requestProtocol
	 * @return 
	 * @see com.fire.control.system.module.device.service.DeviceService#getDeviceGroupInfo(com.fire.control.system.support.protocol.device.DeviceRequestProtocol)
	 */
	@Override
	public ResponseProtocol getDeviceGroupInfo(DeviceRequestProtocol requestProtocol) {
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		String id = requestProtocol.getId();
		if(id != null) {
			GroupListDTO group = deviceGroupMapper.getDetailById(id);
			if(group !=null) {
				String region = group.getMergerName();
				group.setRegion(region.split(","));
			
				ResponseMessage.CODE_200.messageToProtocol(response);
				response.setDate(new XdaoDate());
				response.setData(group);
				return response;
			}
		}
		ResponseMessage.CODE_400.messageToProtocol(response);
		return response;
	}

	/**
	 * <p>Author: xiechengguang</p> 
	 * <p>Title: getDevicesByTreeId</p> 
	 * <p>Description: 根据省、市、区、设备组id及其搜索条件获取其下的对应设备</p> 
	 * @param requestProtocol
	 * @param user
	 * @return 
	 * @see com.fire.control.system.module.device.service.DeviceService#getDevicesByTreeId(com.fire.control.system.support.protocol.device.DeviceRequestProtocol, com.fire.control.system.dto.UserDTO)
	 */
	@Override
	public ResponseProtocol getDevicesByTreeId(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		String id = requestProtocol.getId(); // 省、市、区、设备组的id
		String deviceName = requestProtocol.getDeviceName();  // 根据设备名称模糊匹配
		String onlineStatus = requestProtocol.getOnlineStatus();  // 在线状态搜索
		
		int page = requestProtocol.getCurrentPage();
		int size = requestProtocol.getPageSize();
		List<String> companyIds = companyService.getChildCompanyIdList(user.getCompany().getId());
		
		PageHelper.startPage(page, size);
		List<DeviceListDTO> deviceList = deviceMapper.getDevicesByTreeId(id, companyIds, deviceName, onlineStatus);
		if(deviceList != null && !deviceList.isEmpty()) {
			response.setData(ResultPageUtil.resultPage(new PageInfo<DeviceListDTO>(deviceList), deviceList));
			return response;
		}
		ResponseMessage.CODE_204.messageToProtocol(response);
		
		return response;
	}

	/**
	 * @author: xiechengguang 
	 * @Title: getAllBuildingDevices   
	 * @Description: 根据当前设备获取楼栋所有设备，统计每层  
	 * @param:        
	 * @return: ResponseProtocol      
	 * @throws
	 */
	@Override
	public ResponseProtocol getAllBuildingDevices(DeviceRequestProtocol requestProtocol, UserDTO user) {
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		if(requestProtocol != null) {
			String id = requestProtocol.getId();
			String companyId = user.getCompany().getId();
			// 获取所在设备组id
			String groupId = deviceMapper.getGroupIdByDeviceId(id);
			//获取所在楼栋的每层设备数统计
			List<CountDto> countList = deviceMapper.getAllFloorsById(id, groupId); 
			if(countList != null && !countList.isEmpty()) {
				for(CountDto c : countList) {
					Integer floor = c.getFloor();
					if(floor != null) {
						// 获取每层的设备列表
						List<MapDeviceDTO> deviceList = deviceMapper.eachFloorDevices(floor, groupId);
						c.setList(deviceList);
					}
				}
				ResponseMessage.CODE_200.messageToProtocol(response);
				response.setData(countList);
				return response;
			}
			ResponseMessage.CODE_204.messageToProtocol(response);
			return response;
		}
		ResponseMessage.CODE_400.messageToProtocol(response);
		return response;
	}

	


}
